﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Survival.Services;

namespace Survival.Components
{
        public class DebugText : DrawableGameComponent, IDebugTextService
        {
            ContentManager content;
            SpriteBatch spriteBatch;
            SpriteFont spriteFont;
            List<DrawableString> drawableStringList;

            int frameRate = 0;
            int frameCounter = 0;
            TimeSpan elapsedTime = TimeSpan.Zero;


            public DebugText(Game game)
                : base(game)
            {
                content = new ContentManager(game.Services);
            }

            public override void Initialize()
            {
                base.Initialize();
                drawableStringList = new List<DrawableString>();
            }

            protected override void LoadContent()
            {
                spriteBatch = new SpriteBatch(GraphicsDevice);
                spriteFont = Game.Content.Load<SpriteFont>("font");
            }


            protected override void UnloadContent()
            {
                content.Unload();
            }


            public override void Update(GameTime gameTime)
            {
                elapsedTime += gameTime.ElapsedGameTime;

                if (elapsedTime > TimeSpan.FromSeconds(1))
                {
                    elapsedTime -= TimeSpan.FromSeconds(1);
                    frameRate = frameCounter;
                    frameCounter = 0;
                }
            }


            public override void Draw(GameTime gameTime)
            {
                frameCounter++;

                string fps = string.Format("fps: {0}", frameRate);

                spriteBatch.Begin();

                           spriteBatch.DrawString(spriteFont, fps, Vector2.One, Color.Black);
                           spriteBatch.DrawString(spriteFont, fps, Vector2.Zero, Color.White);
                           DrawAllStrings();

                spriteBatch.End();

                drawableStringList.Clear();
            }

            private void DrawAllStrings()
            {
                foreach (DrawableString drawableString in drawableStringList)
                {
                    spriteBatch.DrawString(spriteFont, drawableString.text, drawableString.position, Color.White);
                }
            }

            public void DrawString(DrawableString drawableString)
            {
                drawableStringList.Add(drawableString);
            }
        }
}
